package com.flymobi.mshop.activity;

import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ExpandableListView.OnChildClickListener;

import com.flymobi.mshop.R;
import com.flymobi.mshop.adapter.ClassListAdapter;
import com.flymobi.mshop.adapter.ImageViewAdapter;
import com.flymobi.mshop.adapter.PersonalCenterAdapter;
import com.flymobi.mshop.adapter.ResultAdapter;
import com.flymobi.mshop.anim.ScrollAnim;
import com.flymobi.mshop.po.Users;
import com.flymobi.mshop.util.Constants;
import com.flymobi.mshop.util.ImageUtil;
import com.flymobi.mshop.util.ShopCarVo;
import com.flymobi.mshop.util.ShopCarVo.Prod;
import com.flymobi.mshop.util.service.ClsService;
import com.flymobi.mshop.util.service.IService;
import com.flymobi.mshop.util.service.OrderService;
import com.flymobi.mshop.util.service.ProductService;
import com.flymobi.mshop.util.service.UsersService;
import com.flymobi.mshop.view.DotView;

/**
 * 
 * @author 余鹏
 * 
 */
public class Main extends CommonActivity implements OnClickListener,
		OnGestureListener, OnTouchListener {
	private RelativeLayout shopping;
	private RelativeLayout gerenzhongxin;
	private RelativeLayout search;
	private RelativeLayout shoppingTrolley;
	private RelativeLayout more;
	private Button btnsearch; // 查询的按钮
	private TextView codeandprice;
	private TextView saleprice;
	private Button btnexit;
	private TextView all;
	public static int WEN = 1;
	private Button btnguang;
	private TextView codeandprices;
	private TextView saleprices;

	private TextView codeandpricess;
	private TextView salepricess;

	private EditText tvsearch; // 查询的文本
	List<Map<String, Object>> classList;

	// <<<<<注册的控件
	private Button btnzhece;
	private EditText etuname;
	private EditText etupwd;
	private EditText etupwd2;
	// 注册的控件>>>>>

	private LinearLayout someProd;

	private String[] imgPathList1;

	private String[] prodPathList;
	AlertDialog dlg;

	private ListView lvresult;
	private LinearLayout lltishi;

	private String[] id;
	public static Users user;

	private ViewGroup middle;
	private View middleCont;
	private ProgressDialog mydialog;
	private ExpandableListView myListView1;
	private String mm;

	DotView addot;

	double allprice = 0;

	private GestureDetector mGestureDetector;
	private ViewFlipper mFlipper;
	private static final int FLING_MIN_DISTANCE = 100;
	private static final int FLING_MIN_VELOCITY = 200;

	private Button exit;

	private void addList(ExpandableListView expandableListView) {
		final ClassListAdapter listitemAdapter = new ClassListAdapter(
				Main.this, classList);
		// 把适配器做完操作以后的数据加到ListView里面
		expandableListView.setAdapter(listitemAdapter);
		// ListView的onclick方法
		expandableListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				Intent intent = new Intent();
				// 键值对传值
				intent.putExtra("id", listitemAdapter.getGroup(groupPosition)
						.get("id").toString());
				intent.putExtra("name", listitemAdapter.getGroup(groupPosition)
						.get("name").toString());
				intent.setClass(Main.this, ClassificationBrowse.class);
				// 启动Activity
				Main.this.startActivity(intent);
				return false;
			}
		});
	}

	Handler hdl = new Handler() {
		// 实现HandlerMessage方法进行操作。
		public void handleMessage(android.os.Message msg) {
			// 如果线程里面的what==0，就进行登录操作
			if (msg.what == 0) {
				mydialog.dismiss();
				Toast.makeText(Main.this, "账号或者密码错误", 40000).show();
				login();
				return;
			}
			if (msg.what == 1) {
				mydialog.dismiss();
				setMiddleCont(R.layout.personalcenter);
				exit.setVisibility(View.VISIBLE);
				imageButton(gerenzhongxin);
				TextView txtUser = (TextView) findViewById(R.id.txtUser);
				txtUser.setText(userName.getText());
				TextView txtUsers = (TextView) findViewById(R.id.txtUsers);
				txtUsers.setText(user.getMobile());
				TextView money = (TextView) findViewById(R.id.money);
				money.setText(user.getMoney().toString());
				mm = money.getText().toString();
				TextView jifen = (TextView) findViewById(R.id.jifen);
				jifen.setText(user.getJifen().toString());
				imgOnclick();
				title.setText(R.string.gerenzhongxin);
				return;
			}
			// 如果线程里面的what==3
			if (msg.what == 3) {
				addList(myListView1);
				// 关闭进度条对话框
				mydialog.dismiss();
				return;
			}
			if (msg.what == 4) {
				// 广告图滚动
				mFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
				addot = (DotView) findViewById(R.id.addot);
				int[] imageIds = new int[7];
				imageIds[0] = R.drawable.loader_frame_1;
				imageIds[1] = R.drawable.loader_frame_2;
				imageIds[2] = R.drawable.loader_frame_3;
				imageIds[3] = R.drawable.loader_frame_4;
				imageIds[4] = R.drawable.loader_frame_5;
				imageIds[5] = R.drawable.loader_frame_6;
				imageIds[6] = R.drawable.loader_frame_7;
				addot.setImageIds(imageIds);
				addot.startAnim(hdl);
				// 注册一个用于手势识别的类
				mGestureDetector = new GestureDetector(Main.this);
				// 给mFlipper设置一个listener
				mFlipper.setOnTouchListener(Main.this);
				// mCurrentLayoutState = 0;
				// 允许长按住ViewFlipper,这样才能识别拖动等手势
				mFlipper.setLongClickable(true);

				// galleryFlow = (GalleryFlow) findViewById(R.id.gallery_flow);
				if (adProdList == null) {
					return;
				}
				imgPathList1 = new String[adProdList.size()];
				int i = 0;
				for (Map<String, Object> prod : adProdList) {
					imgPathList1[i] = prod.get("imgpath").toString();
					ImageView img = new ImageView(Main.this);
					BitmapDrawable bm = new BitmapDrawable(
							ImageUtil.getHttpBitmap(IService.serverUrl
									+ imgPathList1[i]));
					img.setAdjustViewBounds(true);
					img
							.setLayoutParams(new ViewGroup.LayoutParams(
									LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT));
					img.setBackgroundDrawable(bm);
					mFlipper.addView(img);
					i++;
				}
				// 广告图滚动

				// 新品上架
				prodPathList = new String[xinpinshangjia.size()];
				id = new String[xinpinshangjia.size()];
				int m = 0;
				if (prodPathList == null || id == null) {
					Toast.makeText(Main.this, "网络错误，请重试", 40000).show();
					return;
				}
				for (Map<String, Object> prod : xinpinshangjia) {
					prodPathList[m] = prod.get("imgpath").toString();
					id[m] = prod.get("id").toString();
					m++;
				}
				ImageViewAdapter adapter1 = new ImageViewAdapter(Main.this,
						prodPathList, id);
				gallery.setAdapter(adapter1);
				gallery
						.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, final int arg2, long arg3) {
								arg1.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										// TODO Auto-generated metho d stub
										Intent intent = new Intent();
										intent.putExtra("id", id[arg2
												% prodPathList.length]);
										intent.setClass(Main.this,
												BuyShopping.class);
										Main.this.startActivity(intent);
									}
								});
								Map<String, Object> curProd = xinpinshangjia
										.get(arg2 % prodPathList.length);
								codeandprice.setText(curProd.get("name")
										.toString());
								saleprice.setText("惊喜价 ¥"
										+ curProd.get("saleprice").toString());
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								;
							}
						});
				gallery.setSelection(99);
				gallery.setUnselectedAlpha(1);
				// 新品上架

				// 热销商品
				prodPathList = new String[rexiaoshangpin.size()];
				id = new String[rexiaoshangpin.size()];
				int m1 = 0;
				if (prodPathList == null || id == null) {
					Toast.makeText(Main.this, "网络错误，请重试", 40000).show();
					return;
				}
				for (Map<String, Object> prod : rexiaoshangpin) {
					prodPathList[m1] = prod.get("imgpath").toString();
					id[m1] = prod.get("id").toString();
					m1++;
				}
				ImageViewAdapter adapter2 = new ImageViewAdapter(Main.this,
						prodPathList, id);
				gallerys.setAdapter(adapter2);
				gallerys
						.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, final int arg2, long arg3) {
								arg1.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										// TODO Auto-generated metho d stub
										Intent intent = new Intent();
										intent.putExtra("id", id[arg2
												% prodPathList.length]);
										intent.setClass(Main.this,
												BuyShopping.class);
										Main.this.startActivity(intent);
									}
								});
								Map<String, Object> curProd = xinpinshangjia
										.get(arg2 % prodPathList.length);
								codeandprices.setText(curProd.get("name")
										.toString());
								saleprices.setText("惊喜价¥"
										+ curProd.get("saleprice").toString());
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub
								;
							}
						});
				gallerys.setSelection(99);
				// 热销商品

				// 疯狂抢购
				prodPathList = new String[fengkuangqianggou.size()];
				id = new String[fengkuangqianggou.size()];
				int m2 = 0;
				if (fengkuangqianggou == null || id == null) {
					Toast.makeText(Main.this, "网络错误，请重试", 40000).show();
					return;
				}
				for (Map<String, Object> prod : fengkuangqianggou) {
					prodPathList[m2] = prod.get("imgpath").toString();
					id[m2] = prod.get("id").toString();
					m2++;
				}
				ImageViewAdapter adapter3 = new ImageViewAdapter(Main.this,
						prodPathList, id);
				galleryss.setAdapter(adapter3);
				galleryss
						.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, final int arg2, long arg3) {
								arg1.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										// TODO Auto-generated metho d stub
										Intent intent = new Intent();
										intent.putExtra("id", id[arg2
												% prodPathList.length]);
										intent.setClass(Main.this,
												BuyShopping.class);
										Main.this.startActivity(intent);
									}
								});
								Map<String, Object> curProd = xinpinshangjia
										.get(arg2 % prodPathList.length);
								codeandpricess.setText(curProd.get("name")
										.toString());
								salepricess.setText("惊喜价¥"
										+ curProd.get("saleprice").toString());
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								;
							}
						});
				galleryss.setSelection(99);
				// 疯狂抢购
				mydialog.dismiss();
				return;
			}

			if (msg.what == 5) {
				// int index = msg.arg1;
				mFlipper.setInAnimation(ScrollAnim.inFromRightAnimation());
				// 设置View退出屏幕时候使用的动画
				mFlipper.setOutAnimation(ScrollAnim.outToLeftAnimation());
				mFlipper.showNext();
				return;
			}
			if (msg.what == 7) {
				setMiddleCont(R.layout.search_result);
				lvresult = (ListView) findViewById(R.id.lvresult);
				ResultAdapter classIfcation = new ResultAdapter(search2,
						Main.this);
				lvresult.setAdapter(classIfcation);
				mydialog.dismiss();
				return;
			}

			if (msg.what == 10) {
				if (list != null) {
					PersonalCenterAdapter prlc = new PersonalCenterAdapter(
							Main.this, list);
					title.setText(R.string.Myorder);
					listview.setAdapter(prlc);
				} else {
					Toast.makeText(Main.this, "网络错误，请重试", Toast.LENGTH_LONG)
							.show();
				}
				mydialog.dismiss();
			}

		}

	};

	private EditText password;

	private List<Map<String, Object>> adProdList;

	private List<Map<String, Object>> search2;

	private List<Map<String, Object>> xinpinshangjia;

	private Gallery gallery;

	private Gallery gallerys;

	private Gallery galleryss;

	private List<Map<String, Object>> rexiaoshangpin;

	private List<Map<String, Object>> fengkuangqianggou;

	private TextView title;

	private String log = "";

	private EditText userName;
	private CheckBox checkBox;
	private static final String PREFS_NAME = "MyUserInfo";

	private void LoadUserDate() {
		SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);

		if (sp.getBoolean("isSave", false)) {
			String username = sp.getString("name", "");
			String userpassword = sp.getString("password", "");
			if (!("".equals(username) && "".equals(userpassword))) {
				userName.setText(username);
				password.setText(userpassword);
				checkBox.setChecked(true);
			}
		}
	}

	private Button btnlogin;
	private int qq = 0;

	private void login() {
		shopping.setBackgroundResource(R.color.touming);
		gerenzhongxin.setBackgroundResource(R.color.touming);
		shoppingTrolley.setBackgroundResource(R.color.touming);
		search.setBackgroundResource(R.color.touming);
		more.setBackgroundResource(R.color.touming);
		loginInit();

		LoadUserDate();

		btnlogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mydialog = ProgressDialog.show(Main.this, null, "登录中，请稍后...",
						true);
				mydialog.setCancelable(true);
				new Thread() {
					public void run() {
						try {
							// 等待时间为3秒
							sleep(3000);
							// 调用后台方法，获取登录账号和密码
							user = UsersService.login(userName.getText()
									.toString(), password.getText().toString());
							Message msg = new Message();
							if (user == null) {
								// 设置what=0,Handler收到消息进行对应操作
								msg.what = 0;
								qq = 0;
								System.out.println("if user=null：" + qq);
							} else {
								qq = 1;
								System.out.println("if user！=null：" + qq);
								// 载入配置文件
								SharedPreferences sp = getSharedPreferences(
										PREFS_NAME, 0);
								// 写入配置文件
								Editor spEd = sp.edit();
								if (checkBox.isChecked()) {
									spEd.putBoolean("isSave", true);
									spEd.putString("name", userName.getText()
											.toString());
									spEd.putString("password", password
											.getText().toString());
								} else {
									spEd.putBoolean("isSave", false);
									spEd.putString("name", "");
									spEd.putString("password", "");
								}
								spEd.commit();
								// LoadUserDate();
								// 设置what=1,Handler收到消息进行对应操作
								msg.what = 1;
								log = userName.getText().toString();
							}
							// 发消息给Handler吧what传过去，Handler进行判断
							hdl.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
		});
		btnexit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				title.setText("注册");
				setMiddleCont(R.layout.registr);
				zhucekongjian();
				// 注册的布局文件中的，点击注册按钮时发生的事件

			}
		});
	}

	private void loginInit() {
		shopping.setBackgroundResource(R.color.touming);
		gerenzhongxin.setBackgroundResource(R.color.touming);
		shoppingTrolley.setBackgroundResource(R.color.touming);
		search.setBackgroundResource(R.color.touming);
		more.setBackgroundResource(R.color.touming);
		userName = (EditText) findViewById(R.id.userName1);
		password = (EditText) findViewById(R.id.password1);
		checkBox = (CheckBox) findViewById(R.id.checkBox);
		btnlogin = (Button) findViewById(R.id.btnlogin);
		btnexit = (Button) findViewById(R.id.btnzhuce);
	}

	private void zhucekongjian() {
		btnzhece = (Button) findViewById(R.id.btnzhece);
		etuname = (EditText) findViewById(R.id.etuname);
		etupwd = (EditText) findViewById(R.id.etupwd);
		etupwd2 = (EditText) findViewById(R.id.etupwd2);

		btnzhece.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (etupwd.getText().toString().equals(
						etupwd2.getText().toString())) {
					int i = UsersService.reg(etuname.getText().toString(),
							etupwd2.getText().toString());
					if (i == 1) {
						Toast.makeText(Main.this, "注册成功", Toast.LENGTH_LONG)
								.show();
						// setMiddleCont(R.layout.login);
						// login();
					} else {
						Toast.makeText(Main.this, "注册失败", Toast.LENGTH_LONG)
								.show();
					}
				} else {
					Toast.makeText(Main.this, "两次密码不一样!", Toast.LENGTH_LONG)
							.show();
					etupwd.setText("");
					etupwd2.setText("");
				}

			}
		});
	}

	// 下面菜单条点击的时候进行图片切换
	private void imageButton(View v) {
		// 先设置一个背景图片
		shopping.setBackgroundResource(R.color.touming);
		gerenzhongxin.setBackgroundResource(R.color.touming);
		shoppingTrolley.setBackgroundResource(R.color.touming);
		search.setBackgroundResource(R.color.touming);
		more.setBackgroundResource(R.color.touming);
		// 下面进行一些判断，点哪个图片就切换什么图片
		switch (v.getId()) {
		case R.id.homePage:
			v.setBackgroundResource(R.drawable.main_navigation_highlight_bg);
			break;
		case R.id.gerenzhongxin:
			v.setBackgroundResource(R.drawable.main_navigation_highlight_bg);
			break;
		case R.id.search:
			v.setBackgroundResource(R.drawable.main_navigation_highlight_bg);
			break;
		case R.id.shoppingTrolley:
			v.setBackgroundResource(R.drawable.main_navigation_highlight_bg);
			break;
		case R.id.more:
			v.setBackgroundResource(R.drawable.main_navigation_highlight_bg);
			break;
		}
	}

	/**
	 * 查询分类列表
	 */
	private void listCls(final String fatherId) {
		// 先得到ListView控件
		myListView1 = (ExpandableListView) findViewById(R.id.listclsview1);
		myListView1.setCacheColorHint(R.color.touming);
		// 打开一个模式化进度条对话框
		mydialog = ProgressDialog.show(Main.this, null, "loading...", true);
		mydialog.setCancelable(true);
		// 新建一个线程
		new Thread() {
			public void run() {
				try {
					// 调用后台查询分类列表的方法，参数传一个id
					classList = ClsService.listCls(fatherId);
					Message msg = new Message();
					// 设置whet=3,Handler收到消息进行对应操作
					msg.what = 3;
					// 发消息给Handler吧what传过去，Handler进行判断
					hdl.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	// private Order

	// 购物车
	private void shoppingCar() {
		ShopCarVo scv = ShopCarVo.getInstance();
		TextView count = (TextView) findViewById(R.id.count);
		if (scv.getCount() == 0) {
			setMiddleCont(R.layout.shoppingcar);
			btnguang = (Button) findViewById(R.id.btnguangguang);
			btnguang.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					setMiddleCont(R.layout.home);
					init();
				}
			});
			count.setVisibility(View.GONE);
		} else {
			count.setVisibility(View.VISIBLE);
			System.out.println("count:" + scv.getCount());
			count.setText(scv.getCount() + "");
			Set<Prod> list = scv.getProdList();
			setMiddleCont(R.layout.shopcar);
			someProd = (LinearLayout) findViewById(R.id.someProd);
			for (Prod prod : list) {
				TextView tv = new TextView(Main.this);
				LinearLayout ll = new LinearLayout(Main.this);
				TextView bianhao = new TextView(Main.this);
				TextView code = new TextView(Main.this);
				LinearLayout lay = new LinearLayout(Main.this);
				TextView quantity = new TextView(Main.this);
				EditText et = (EditText) View.inflate(Main.this,
						R.layout.column, null);
				TextView jiage = new TextView(Main.this);
				TextView price = new TextView(Main.this);
				ll.setOrientation(LinearLayout.HORIZONTAL);
				lay.setOrientation(LinearLayout.HORIZONTAL);
				bianhao.setText("编号:");
				quantity.setText("数量:");
				jiage.setText("价格:");
				et.setText(prod.getCount() + "");
				price.setText(prod.getProd().get("saleprice").toString());
				code.setText(prod.getProd().get("code").toString());
				Log.d("test", "" + prod.getProd().get("name").toString());
				tv.setText(prod.getProd().get("name").toString());
				System.out.println(tv.getText());
				someProd.addView(tv);
				ll.addView(bianhao);
				ll.addView(code);
				lay.addView(quantity);
				lay.addView(et);
				lay.addView(jiage);
				lay.addView(price);
				someProd.addView(ll);
				someProd.addView(lay);
				double pri = new Double(prod.getProd().get("saleprice")
						.toString());
				int shu = new Integer(prod.getCount() + "");
				double prodprice = pri * shu;
				allprice = allprice + prodprice;
			}
			all = new TextView(Main.this);
			all.setText(allprice + "");
			someProd.addView(all);
			Button suan = new Button(Main.this);
			suan.setId(1);
			suan.setText("去结算");
			someProd.addView(suan);
			suan.setOnClickListener(this);
		}
		init();
		title.setText("购物车");
		imageButton(shoppingTrolley);
	}

	// 同上
	private void listProd(final String rank) {
		// 同上
		mydialog = ProgressDialog.show(Main.this, null, "数据加载中...", true);
		mydialog.setCancelable(true);
		// 同上
		new Thread() {
			public void run() {
				try {
					// 同上，多了一个排序rank，这是一个排序的参数，Constants.Cls.ad是一个自己定义的常量
					adProdList = ProductService.list(Constants.Cls.ad, rank);
					xinpinshangjia = ProductService.list(
							Constants.Cls.xinpinshangjia, rank);
					rexiaoshangpin = ProductService.list(
							Constants.Cls.rexiaoshangpin, rank);
					fengkuangqianggou = ProductService.list(
							Constants.Cls.fengkuangqianggou, rank);
					Message msg = new Message();
					msg.what = 4;
					hdl.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private ListView listview;

	// 按钮的单击事件，动态加载中间部分的内容
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.homePage:
			// 调用底部图片切换的方法
			imageButton(shopping);
			// 加载布局文件，吧中间的部分改为R.layout.home这个布局
			setMiddleCont(R.layout.home);
			exit.setVisibility(View.GONE);
			init();
			addEnt();
			// 把标题改为shopping
			title.setText(R.string.shopping);
			break;
		case R.id.gerenzhongxin:
			if (log.equals("") || log == null) {
				title.setText(R.string.login);
				setMiddleCont(R.layout.login);
				login();
			} else {
				// 把标题改为classification
				title.setText(R.string.gerenzhongxin);
				setMiddleCont(R.layout.personalcenter);
				exit.setVisibility(View.VISIBLE);
				// 把登录按钮隐藏
				imageButton(gerenzhongxin);
				TextView txtUser = (TextView) findViewById(R.id.txtUser);
				txtUser.setText(userName.getText());
				TextView txtUsers = (TextView) findViewById(R.id.txtUsers);
				txtUsers.setText(user.getMobile());
				TextView money = (TextView) findViewById(R.id.money);
				money.setText(user.getMoney().toString());
				TextView jifen = (TextView) findViewById(R.id.jifen);
				jifen.setText(user.getJifen().toString());
				imgOnclick();
			}
			break;
		case R.id.search:
			init();
			addEnt();
			// 把标题改为search
			title.setText(R.string.search);
			exit.setVisibility(View.GONE);
			// 调用底部图片切换的方法
			imageButton(search);
			setMiddleCont(R.layout.search);
			btnsearch = (Button) findViewById(R.id.btnsearch); // 查找出搜索的按钮
			tvsearch = (EditText) findViewById(R.id.searchText); // 查找出搜索中的文体内容
			btnsearch.setOnClickListener(this);// 搜索商品的事件
			break;
		case R.id.shoppingTrolley:
			title.setText(R.string.shoppingTrolley);
			imageButton(shoppingTrolley);
			allprice = 0;
			shoppingCar();
			exit.setVisibility(View.GONE);
			break;
		case R.id.more:
			title.setText(R.string.more);
			imageButton(more);
			setMiddleCont(R.layout.more);
			exit.setVisibility(View.GONE);

			LinearLayout ccc = (LinearLayout) findViewById(R.id.ccc);
			LinearLayout bbb = (LinearLayout) findViewById(R.id.bbb);
			LinearLayout xxx = (LinearLayout) findViewById(R.id.xxx);
			LinearLayout aaa = (LinearLayout) findViewById(R.id.aaa);

			aaa.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					title.setText(R.string.feedback);
					setMiddleCont(R.layout.yijianfankui);
				}
			});

			xxx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					title.setText(R.string.help);
					setMiddleCont(R.layout.help);
				}
			});

			bbb.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					title.setText(R.string.intr);
					setMiddleCont(R.layout.intr);
				}
			});
			ccc.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					LayoutInflater factory = LayoutInflater.from(Main.this);
					final View DialogView = factory.inflate(R.layout.tishi,
							null);
					dlg = new AlertDialog.Builder(Main.this).setTitle("是否退出系统")
							.setView(DialogView).setPositiveButton("确定",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// MyApplication.getInstance().exit();
										}
									}).setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dlg.dismiss();
											return;
										}
									}).create();
					dlg.show();
				}
			});
			LinearLayout liner = (LinearLayout) findViewById(R.id.liner);
			liner.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 把标题改为search
					Intent intent = new Intent();
					intent.setClass(Main.this, ActKeywordAnim.class);
					Main.this.startActivity(intent);
				}
			});
			break;
		case R.id.btnsearch:
			// 调用搜索内容的方法
			select();
			break;
		case R.id.exit:
			setMiddleCont(R.layout.home);
			imageButton(shopping);
			exit.setVisibility(View.GONE);
			userName.setText("");
			password.setText("");
			log = "";
			break;
		case 1:
			System.out.println("user:" + qq);
			if (qq == 0) {
				setMiddleCont(R.layout.login);
				loginInit();
				login();
			}
			if (qq == 1) {
				System.out.println(Float.parseFloat(allprice + ""));
				double f = allprice;
				FillOrder.valueMap.put("money", f);
				Intent intent = new Intent();
				FillOrder.valueMap.put("yue", mm);
				intent.setClass(Main.this, FillOrder.class);
				Main.this.startActivity(intent);
			}
		}

	}

	private void imgOnclick() {
		LinearLayout dingdan = (LinearLayout) findViewById(R.id.dingdan);
		LinearLayout shoucang = (LinearLayout) findViewById(R.id.shoucang);
		dingdan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setMiddleCont(R.layout.listdata);
				exit.setVisibility(View.GONE);
				listview = (ListView) findViewById(R.id.orderListView);
				long id = user.getId();
				queryOrder(id);
			}
		});
		shoucang.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				exit.setVisibility(View.GONE);
				Toast.makeText(Main.this, "收藏功能维护中", Toast.LENGTH_SHORT).show();
			}
		});
	}

	List<Map<String, Object>> list;

	private void queryOrder(final long usersId) {
		mydialog = ProgressDialog.show(Main.this, null, "loading...", true);
		mydialog.setCancelable(true);
		// 新建一个线程
		new Thread() {
			public void run() {
				try {
					// 调用后台查询分类列表的方法，参数传一个id
					list = OrderService.list(usersId);

					Message msg = new Message();
					// 设置whet=10,Handler收到消息进行对应操作
					msg.what = 10;
					// 发消息给Handler吧what传过去，Handler进行判断
					hdl.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	// 查询搜索中的数据
	private void select() {
		mydialog = ProgressDialog.show(Main.this, null, "数据加载中...", true);
		mydialog.setCancelable(true);
		new Thread() {
			public void run() {
				try {
					search2 = ProductService.list(
							tvsearch.getText().toString(), Constants.Cls.ad,
							null);
					System.out.println("文本框=" + tvsearch.getText());
					System.out.println("search2=" + search2);
					Message msg = new Message();
					msg.what = 7;
					if (search2 == null) {
						setMiddleCont(R.layout.tishi);
						lltishi = (LinearLayout) findViewById(R.id.lltishi);
						TextView tvts = new TextView(Main.this);
						tvts.setText("对不起,没有找到与 " + tvsearch.getText()
								+ " 相关的商品");
						tvts.setTextColor(R.color.heise);
						tvts.setTextSize(14);
						Button btnfanhui = new Button(Main.this);
						// 动态加载相应的 控件,文本,按钮
						lltishi.addView(tvts);
						lltishi.addView(btnfanhui);

						btnfanhui.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								setMiddleCont(R.layout.search);
							}
						});
						return;
					}
					hdl.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		if (WEN == 1) {
			setMiddleCont(R.layout.);
		}
		if (WEN == 2) {
			shoppingCar();
			WEN = 1;
		}
		// 初始化控件
		init();
		// 为控件绑定事件
		addEnt();

		// MyApplication.getInstance().addActivity(this);
	}

	private void addEnt() {
		shopping.setOnClickListener(this);
		gerenzhongxin.setOnClickListener(this);
		search.setOnClickListener(this);
		shoppingTrolley.setOnClickListener(this);
		more.setOnClickListener(this);
		exit.setOnClickListener(this);

	}

	private void init() {
		shopping = (RelativeLayout) findViewById(R.id.homePage);
		gerenzhongxin = (RelativeLayout) findViewById(R.id.gerenzhongxin);
		search = (RelativeLayout) findViewById(R.id.search);
		shoppingTrolley = (RelativeLayout) findViewById(R.id.shoppingTrolley);
		more = (RelativeLayout) findViewById(R.id.more);
		title = (TextView) findViewById(R.id.title);
		gallery = (Gallery) findViewById(R.id.gallery);
		gallerys = (Gallery) findViewById(R.id.gallerys);
		galleryss = (Gallery) findViewById(R.id.galleryss);
		codeandprice = (TextView) findViewById(R.id.codeandprice);
		saleprice = (TextView) findViewById(R.id.saleprice);
		codeandprices = (TextView) findViewById(R.id.codeandprices);
		saleprices = (TextView) findViewById(R.id.saleprices);
		codeandpricess = (TextView) findViewById(R.id.codeandpricess);
		salepricess = (TextView) findViewById(R.id.salepricess);
		exit = (Button) findViewById(R.id.exit);
	}

	// meun菜单的方法
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, R.string.homePage);
		menu.add(0, 2, 2, R.string.search);
		menu.add(0, 3, 3, R.string.shoppingTrolley);
		menu.add(0, 4, 4, R.string.dingdan);
		menu.add(0, 5, 5, R.string.shoucang);
		menu.add(0, 6, 6, R.string.exit);
		return true;
	}

	// meun菜单的一些操作
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			break;
		case 2:
			break;
		case 3:
			break;
		case 4:
			break;
		case 5:
			break;
		case 6:
			// 关闭按钮
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 动态加载布局
	private void setMiddleCont(int layout) {
		middle = (ViewGroup) findViewById(R.id.middle);
		middleCont = View.inflate(Main.this, layout, null);
		middle.removeAllViews();
		middle.addView(middleCont);
		switch (layout) {
		case R.layout.home:
			listProd("");
			break;
		case R.layout.search:
			ExpandableListView view1 = new ExpandableListView(this);
			view1.setId(R.id.listclsview1);
			view1.setCacheColorHint(R.color.touming);
			ExpandableListView.LayoutParams lp1 = new ExpandableListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.FILL_PARENT);
			view1.setLayoutParams(lp1);
			view1.setFadingEdgeLength(0);
			middle.addView(view1);
			init();
			addEnt();
			listCls("0");
			break;
		}
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// 当像左侧滑动的时候
			// 设置View进入屏幕时候使用的动画
			mFlipper.setInAnimation(ScrollAnim.inFromRightAnimation());
			// 设置View退出屏幕时候使用的动画
			mFlipper.setOutAnimation(ScrollAnim.outToLeftAnimation());
			mFlipper.showNext();
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// 当像右侧滑动的时候
			mFlipper.setInAnimation(ScrollAnim.inFromLeftAnimation());
			mFlipper.setOutAnimation(ScrollAnim.outToRightAnimation());
			mFlipper.showPrevious();
		}
		return false;

	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return mGestureDetector.onTouchEvent(event);
	}

}
